import config from '@/config/app.js'

const userApi = {
	/**
	 * 测试连接
	 */
	testConnection() {
		console.log('API: 测试连接，baseUrl:', config.AI_HTTP_REQUEST_URL);
		return new Promise((resolve, reject) => {
			uni.request({
				url: config.AI_HTTP_REQUEST_URL + '/auth/user-info',
				method: 'GET',
				header: {
					'token': uni.getStorageSync('token')
				},
				success: (res) => {
					console.log('API: 测试连接成功:', res);
					resolve(res);
				},
				fail: (error) => {
					console.error('API: 测试连接失败:', error);
					reject(error);
				}
			});
		});
	},

	/**
	 * 上传并保存头像（完整流程）
	 * @param {String} filePath 本地图片路径
	 * @returns {Promise}
	 */
	uploadAndSaveAvatar(filePath) {
		console.log('API: 开始上传并保存头像，文件路径:', filePath);

		return new Promise((resolve, reject) => {
			const token = uni.getStorageSync('token');
			console.log('API: 获取到的token:', token);

			// 第一步：上传图片
			uni.uploadFile({
				url: config.AI_HTTP_REQUEST_URL + '/upload/oss/image',
				filePath: filePath,
				name: 'file',
				header: {
					'token': token
				},
				success: (uploadRes) => {
					console.log('API: 上传原始响应:', uploadRes);
					console.log('API: 响应状态码:', uploadRes.statusCode);
					console.log('API: 响应数据:', uploadRes.data);

					try {
						const uploadData = JSON.parse(uploadRes.data);
						console.log('API: 解析后的上传数据:', uploadData);

						if (uploadData.code === 200 && uploadData.data && uploadData.data.url) {
							const avatarUrl = uploadData.data.url;
							console.log('API: 图片上传成功，URL:', avatarUrl);

							// 第二步：保存头像链接到数据库
							uni.request({
								url: config.AI_HTTP_REQUEST_URL + '/auth/update-avatar',
								method: 'POST',
								data: {
									avatar: avatarUrl
								},
								header: {
									'token': token,
									'Content-Type': 'application/json'
								},
								success: (updateRes) => {
									console.log('API: 更新头像响应:', updateRes);
									
									if (updateRes.data.code === 200) {
										console.log('API: 头像保存成功');
										resolve({
											code: 200,
											message: '头像更新成功',
											data: {
												avatar: avatarUrl,
												uploadResult: uploadData,
												updateResult: updateRes.data
											}
										});
									} else {
										console.log('API: 头像保存失败:', updateRes.data.message);
										reject(new Error(updateRes.data.message || '保存头像失败'));
									}
								},
								fail: (updateError) => {
									console.error('API: 保存头像请求失败:', updateError);
									reject(new Error('保存头像网络请求失败'));
								}
							});

						} else {
							console.log('API: 图片上传失败，错误信息:', uploadData.message);
							reject(new Error(uploadData.message || '图片上传失败'));
						}
					} catch (e) {
						console.error('API: 解析上传响应数据失败:', e);
						console.error('API: 原始响应数据:', uploadRes.data);
						reject(new Error('上传响应数据格式错误'));
					}
				},
				fail: (uploadError) => {
					console.error('API: 上传请求失败:', uploadError);
					reject(new Error('图片上传网络请求失败'));
				}
			});
		});
	}
}

export default userApi 